package com.pubinfo.passbook.common.service.master.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.pubinfo.passbook.common.entity.*;
import com.pubinfo.passbook.common.exception.ServiceException;
import com.pubinfo.passbook.common.mapper.*;
import com.pubinfo.passbook.common.model.bo.uccp.ShortMessageParam;
import com.pubinfo.passbook.common.model.bo.witeoff.MedicineOnJobOrRetireBO;
import com.pubinfo.passbook.common.model.constant.LogNameEnum;
import com.pubinfo.passbook.common.model.dto.rule.RuleAuditChangeParam;
import com.pubinfo.passbook.common.model.dto.rule.RuleAuditParam;
import com.pubinfo.passbook.common.model.dto.witeoff.MedicineOnJobOrRetireDTO;
import com.pubinfo.passbook.common.model.http.eip.UserInfo;
import com.pubinfo.passbook.common.model.vo.rule.AuditDetailVo;
import com.pubinfo.passbook.common.model.vo.rule.TRuleAuditDetailVo;
import com.pubinfo.passbook.common.service.dubbo.DubboService;
import com.pubinfo.passbook.common.service.master.*;
import com.pubinfo.passbook.common.service.mss.HttpService;
import com.pubinfo.passbook.common.service.ruler.CheckService;
import com.pubinfo.passbook.common.utils.UccpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

import static com.pubinfo.passbook.common.model.constant.RoleEnum.ADMIN;
import static com.pubinfo.passbook.common.model.constant.RoleEnum.AUDITOR;

/**
 *
 */
@Service
public class TRuleAuditServiceImpl extends ServiceImpl<TRuleAuditMapper, TRuleAudit>
    implements TRuleAuditService {
    @Autowired
    HttpService httpService;
    @Autowired
    TFileInfoMapper tFileInfoMapper;
    @Autowired
    DubboService dubboService;
    @Resource
    private CheckService userInfoService;
    @Autowired
    TSourceArtificialMapper tSourceArtificialMapper;
    @Autowired
    TSourcePassbookMapper tSourcePassbookMapper;
    @Autowired
    private TSyncLogService kafkaSender;
    @Autowired
    DubboService vatService;
    @Autowired
    TWiteoffInstanceMapper tWiteoffInstanceMapper;
    @Autowired
    TPassbookService passbookService;
    @Autowired
    TRabbitmqPersonConvertService tRabbitmqPersonConvertService;
    @Autowired
    TWiteoffInstanceSubitemMapper tWiteoffInstanceSubitemMapper;

    @Override
    public IPage<TRuleAuditDetailVo> selectRuleAudit(RuleAuditParam param, UserInfo userInfo, String currentAcct) {
        List<OrderItem> orderItems=new ArrayList<>();
        OrderItem orderItem=new OrderItem();
        orderItem.setAsc(false);
        orderItem.setColumn("create_time");
        orderItems.add(orderItem);
        param.setOrders(orderItems);
        IPage<TRuleAuditDetailVo> iPage = page(param.getPage());
        if (userInfoService.judgeRole(AUDITOR.getRoleCode(), userInfo)) {
            param.setAcct(currentAcct);
            return this.baseMapper.selectRuleAudit(iPage, param);
        } else if (userInfoService.judgeRole(ADMIN.getRoleCode(), userInfo)) {
            return this.baseMapper.selectRuleAudit(iPage, param);
        } else {
            throw new ServiceException("当前用户没有权限");
        }
    
    }

    @Override
    public AuditDetailVo  getAuditDetail(String witeoffId) {
        AuditDetailVo detailVo = this.baseMapper.getAuditDetail(witeoffId);
        if(ObjectUtils.isEmpty(detailVo))
        {
            detailVo = this.baseMapper.getAuditDetailById(witeoffId);
        }
        List<TFileInfo> tFileInfos=tFileInfoMapper.selectFileByWiteoffId(detailVo.getOtherSystemMainId());
        tFileInfos.addAll(tFileInfoMapper.selectEnclosureByWiteoffId(detailVo.getOtherSystemMainId()));
        tFileInfos.addAll(tFileInfoMapper.selectArtificialFIleById(detailVo.getOtherSystemMainId()));
        detailVo.setTFileInfos(tFileInfos);
        detailVo.setTPassbooks(tSourcePassbookMapper.selectPassbookByOtherSystemMainId(detailVo.getOtherSystemMainId()));
        detailVo.setTSourceArtificials(tSourceArtificialMapper.selectArtificialByOtherSystemMainId(detailVo.getOtherSystemMainId()));
        return detailVo;
    }

    @Override
    public Boolean changeAudit(RuleAuditChangeParam param,String acct) {

        TRequestLog syncLog = new TRequestLog();
        syncLog.setType(1).setParam(JSONObject.toJSONString(param)).setUrl("audit/manager/changeAudit").setStatus(2).setName(LogNameEnum.FETCH_PAGE.getCode());
        kafkaSender.save(syncLog);

        TRuleAudit tRuleAudit=this.baseMapper.getAuditByWiteoffId(param.getWiteoffId());

        UpdateWrapper<TRuleAudit> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("witeoffId", param.getWiteoffId());
        updateWrapper.set("status", param.getStatus());
        updateWrapper.set("detail", param.getDetail());
        updateWrapper.set("acct",acct);
        update(updateWrapper);

        if (param.getStatus() == 1) {
            //在处理待办后，发送消息到eip，清空待办
            dubboService.finishedTask(tRuleAudit.getId()); //生产接口上线后，再打开
            return httpService.postByOtherSystemMainId(param.getWiteoffId());
        }
        else if(param.getStatus() == 2)
        {
            TWiteoffInstance tWiteoffInstance=tWiteoffInstanceMapper.selectTwiteoffInstanceByOtherSystemMainId(param.getWiteoffId());
            MedicineOnJobOrRetireDTO jobDTO = JSONObject.toJavaObject(tWiteoffInstance.getJson(), MedicineOnJobOrRetireDTO.class);
            MedicineOnJobOrRetireBO bo = new MedicineOnJobOrRetireBO(jobDTO);
            dubboService.finishedTask(tRuleAudit.getId()); //生产接口上线后，再打开
            tSourceArtificialMapper.updateSystemIsLocked(param.getWiteoffId());
            tSourcePassbookMapper.updateSystemIsLocked(param.getWiteoffId());
            List<TPassbook> tPassbooks = passbookService.getPassbookById(bo.getInvoiceIds());
            return vatService.sendShortMessage(new ShortMessageParam("您好!您于"+ UccpUtil.getSubmitDate(tPassbooks)
                    +"提交单位报销的医药费票据共"+bo.getInvoiceIds().size()+"张，审核意见:"+param.getDetail()
                    +"，审核人:"+tRabbitmqPersonConvertService.getPersonByAcct(tRuleAudit.getAcct()).getTbPersonnel().get("psnName")+"。"
                    ,tWiteoffInstance.getPhone()));
//            return true;
        }
        return true;
    }

    @Override
    @Transactional
    public Boolean deleteAudit(String otherSystemMainId) {

        TRuleAudit tRuleAudit=this.baseMapper.getAuditByWiteoffId(otherSystemMainId);

        //1.删除待办
        QueryWrapper<TRuleAudit> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("witeoffId",otherSystemMainId);
        this.baseMapper.delete(queryWrapper);
        //2.删除eip首页的待办
        dubboService.finishedTask(tRuleAudit.getId());
        //3.解锁相关票据和手工报账
        tSourceArtificialMapper.updateSystemIsLocked(otherSystemMainId);
        tSourcePassbookMapper.updateSystemIsLocked(otherSystemMainId);


        TWiteoffInstance tWiteoffInstance=tWiteoffInstanceMapper.selectTwiteoffInstanceByOtherSystemMainId(otherSystemMainId);

        //4.删除报账单子单
        QueryWrapper<TWiteoffInstanceSubitem> tWiteoffInstanceSubitemQueryWrapper=new QueryWrapper<>();
        queryWrapper.eq("witeoff_instance_id",otherSystemMainId);
        tWiteoffInstanceSubitemMapper.delete(tWiteoffInstanceSubitemQueryWrapper);

        //5.删除票据和手工报账的关联
        tSourceArtificialMapper.deleteArtificialWiteoff(otherSystemMainId);
        tSourcePassbookMapper.deletePassbookWiteoff(tWiteoffInstance.getId());

        //6.删除报账单
        QueryWrapper<TWiteoffInstance> tWiteoffInstanceQueryWrapper=new QueryWrapper<>();
        if(tWiteoffInstanceMapper.deleteInstance(otherSystemMainId))return true;
        throw new ServiceException("删除失败");
    }

}




